# coding=utf-8
import time

import traceback
from monthdelta import monthdelta
import requests
from pymongo import MongoClient
import Utils
import sys
from datetime import datetime
from pandas import DataFrame
import pandas as pd
import json

import pymongo
reload(sys)
sys.setdefaultencoding('utf-8')


mgClient = MongoClient('121.40.54.235', 27017,
    username='root2',
    password='Dream2015',
    authSource="stockDataStore",
    authMechanism='SCRAM-SHA-1')
db = mgClient['stockDataStore']

''' 
def remove_period(table):
    all = db[table].find({})
    for record in all:
        if "报表日期" in record[u'item_names']:
            record[u'item_names'].remove("报表日期")
            db[table].update_one({"_id": record[u'_id']}, {'$set': {'item_names': record[u'item_names'], 'code': record[u'code']}})


#remove_period("balance_sheet_profile")
remove_period("profit_statement_profile")
remove_period("cash_flow_profile")
'''

def repair_peg(stocks):
    table = 'stock_daily_k'
    for stock in stocks:
        if stock['code'] == '600009':#忽略上海机场
            continue
        Utils.logger.info("--->repair peg of stock of " + stock["code"] + " " + stock["name"])
        all = db[table].find({'code': stock['code']})
        all = list(all)
        total_count = len(all)
        success_count = 0
        for record in all:
            try:
                peg = record[u'peg'];
                peg = peg/100
                db[table].update_one({"_id": record[u'_id']},
                                     {'$set': {'peg': peg,
                                               'code': record[u'code'],
                                               'modifyTime': datetime.now()}})
                success_count = success_count +1
            except:
                traceback.print_exc()
        Utils.logger.info("--->end repairing peg of stock of " + stock["code"] + " " + stock["name"] + " total/success: " + str(total_count) + "/" + str(success_count) + "\n")




def main():
    stocks = Utils.quick_access_cursor(db['stock'].find({"code": {"$regex": "^00"}}, projection={"code": 1, "name": 1}, sort=[("code", 1)]));
    repair_peg(stocks)
    stocks = Utils.quick_access_cursor(db['stock'].find({"code": {"$regex": "^30"}}, projection={"code": 1, "name": 1}, sort=[("code", 1)]));
    repair_peg(stocks)
    stocks = Utils.quick_access_cursor(db['stock'].find({"code": {"$regex": "^60"}}, projection={"code": 1, "name": 1}, sort=[("code", 1)]));
    repair_peg(stocks)
main()

#stocks=[{"code":'600009', 'name':'上海机场'}]
#repair_peg(stocks)
